package com.zjhd.sealcutting.Interceptor;

import com.zjhd.sealcutting.dao.MemberSessionidMapper;
import com.zjhd.sealcutting.domain.UserInfo;
import com.zjhd.sealcutting.exception.BizException;
import com.zjhd.sealcutting.utils.CookieUtil;
import com.zjhd.sealcutting.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO  自定义拦截器，实现校验用户是否登陆，未登录返回错误信息：尚未登陆。登陆成功则放行
 *
 * @author wangchao
 * @version 1.0
 * @date 2020/11/24 10:43
 */
@Component
@Slf4j
public class SessionInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private MemberSessionidMapper memberSessionidMapper;

    /**
     * TODO 请求处理前调用,我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
     * @author wangchao
     * @date 2020/11/24 10:44
     * @param
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
            log.info("=============呜呜啦啦，进入拦截器了=================================");
            String authorization=null;
            if(CookieUtil.get(request,"Authorization")!=null){
                authorization = CookieUtil.get(request,"Authorization").getValue();
            }
            if(StringUtils.isEmpty(authorization)){
                authorization = request.getHeader("Authorization");
            }
            if(StringUtils.isEmpty(authorization)){
                log.info("调用接口拦截验证登陆信息不存在，说明状态为未登陆！");
                throw new BizException("4005","无token，请重新登录");
            }else{
                //验证token是否过期
                TokenUtil.checkTokenIsLev(null,authorization);
                UserInfo userInfo=null;
                try {
                    userInfo = TokenUtil.parseAccessToken(authorization);
                    if(userInfo==null){
                        throw new BizException("4005","token失效，请重新登录");
                    }
                    String mobile = userInfo.getMobile();
                    log.info("调用接口拦截验证登陆信息mobile:"+mobile+"存在，说明状态为已登陆！");
                    String sessionId = request.getSession().getId();
                    String newSessionId=memberSessionidMapper.queryByMsId(userInfo.getId());
                    if(StringUtils.isNotBlank(newSessionId)){
                        if(!newSessionId.equals(sessionId)){
                            //用户在另一地方登录 当前下线
                            System.out.println("用户在另一地方登录---用户名："+userInfo.getUserName()+",当前请求sessionId:"+sessionId+"---数据库存放sessionID："+newSessionId);
                            throw new BizException("4006","当前用户在另一地方登录，你已下线！");
                        }
                    }else {
                        throw new BizException("4005","用户已退出，token失效，请重新登录");
                    }
                    return true;
                } catch (BizException e) {
                    e.printStackTrace();
                    throw new BizException(e.getResponseCode(),e.getResponseMessage());
                }catch (Exception e){
                    e.printStackTrace();
                    throw new BizException("4005","token异常，请重新登录");
                }
            }
    }

    //渲染ModelAndView后调用
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("=============呜呜啦啦，进入拦截器了,渲染ModelAndView后调用。=================================");
    }

}
